using Bzstd.Utility;
using Bzstd.Utility.Assertion;

namespace Bzstd.Entity;

public class GameInfo
{
	public uint ConsumerAppId { get; init; }
	public uint CreatorAppId { get; init; }
	public uint[] SearchAppIds { get; init; }
	public WorkshopType WorkshopType { get; init; }
	public ushort Port { get; init; }

	public override string ToString()
	{
		return $"{nameof(ConsumerAppId)}: {ConsumerAppId}, {nameof(CreatorAppId)}: {CreatorAppId}, {nameof(SearchAppIds)}: {string.Join('|', SearchAppIds)}, {nameof(WorkshopType)}: {WorkshopType}, {nameof(Port)}: {Port}";
	}

	public static GameInfo LoadFromCommandLineArgs()
	{
		try
		{
			var commandLineArgs = ConfigHelper.CommandLineArgs;
			Assert.IsTrue(commandLineArgs.Length > 1, "No command line args");
			var args = commandLineArgs[1].Split('-');
			Assert.IsTrue(args.Length > 2, $"Too few args: {args.Length}");
			var appIds = args[0].Split("|");

			Assert.IsTrue(appIds.Length > 0, "No appIds");

			uint consumerAppId, creatorAppId;
			{
				Assert.IsTrue(uint.TryParse(appIds[0], out consumerAppId), $"Invalid appId: {appIds[0]}");
				if (appIds.Length > 1 && !string.IsNullOrWhiteSpace(appIds[1]))
				{
					Assert.IsTrue(uint.TryParse(appIds[1], out creatorAppId), $"Invalid appId: {appIds[1]}");
				}
				else
				{
					creatorAppId = consumerAppId;
				}
			}

			uint[] searchAppIds;
			if (creatorAppId == consumerAppId)
			{
				searchAppIds = appIds
					.Where(appId => !string.IsNullOrWhiteSpace(appId))
					.Select(appIdStr => uint.TryParse(appIdStr, out uint appId) ? appId : Assert.Fail<uint>($"Invalid appId: {appIdStr}"))
					.Distinct()
					.ToArray();
			}
			else
			{
				searchAppIds = [creatorAppId];
			}

			Assert.IsTrue(Enum.TryParse(args[1], out WorkshopType workshopType) && Enum.IsDefined(workshopType), $"Invalid workshopType: {args[1]}");
			Assert.IsTrue(ushort.TryParse(args[2], out ushort port), $"Invalid port: {args[2]}");

			return new GameInfo
			{
				ConsumerAppId = consumerAppId,
				CreatorAppId = creatorAppId,
				SearchAppIds = searchAppIds,
				WorkshopType = workshopType,
				Port = port
			};
		}
		catch (Exception e)
		{
			MessageBox.Show(e.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
			Environment.Exit(1);
			throw;
		}
	}
}

public enum WorkshopType
{
	SteamRemoteStorage,
	UserGeneratedContent
}
